/*global define, require */

define(function (require, exports, module) {

    'use strict';

    var angular = require('angular'),
        services = require('services/services'),
        config = require('config'),
        controllers = angular.module('app.controllers', ['app.services', 'app.config']);

    controllers.controller('IndexCtrl', require('controllers/IndexCtrl'));
    controllers.controller('LoginCtrl', require('controllers/LoginCtrl'));
    controllers.controller('product_IndexCtrl', require('controllers/product/IndexCtrl'));
    controllers.controller('account_IndexCtrl', require('controllers/account/IndexCtrl'));
    //初始化
    controllers.run(['$rootScope','$state', '$ionicHistory', 'LocalCacheService','BASE_PATH',
        '$http','offline','CacheFactory','$cordovaNetwork','PULLING_TEXT','REFRESHING_TEXT',
        function ($rootScope, $state, $ionicHistory, LocalCacheService, BASE_PATH, $http, offline,
                  CacheFactory, $cordovaNetwork, PULLING_TEXT, REFRESHING_TEXT) {

            $http.defaults.cache = CacheFactory.createCache('offlineCache', {deleteOnExpire: 'none',
                maxAge: 0,storageMode: 'localStorage',storagePrefix : "tfzq."});

            offline.start($http);

            $rootScope.basePath = BASE_PATH;
            $rootScope.PULLING_TEXT = PULLING_TEXT;
            $rootScope.REFRESHING_TEXT = REFRESHING_TEXT;
            $rootScope.isOffline = false;
            $rootScope.$on('$cordovaNetwork:online', function(event, networkState){
                $rootScope.isOffline = false;
            });
            $rootScope.$on('$cordovaNetwork:offline', function(event, networkState){
                console.log("got offline");
                $rootScope.isOffline = true;

            })

            $rootScope.closeDigitalKeyboard = function(){ //关闭数字键盘
                if(typeof DigitalKeyboard !== 'undefined') {
                    DigitalKeyboard.close(function(status){});
                }
            };

            $rootScope.goIndex = function(){
                if(typeof Messenger != 'undefined') {
                    Messenger.sendMsg("ym_event",{eventID:"s27"},null,null);
                }
                $state.go("tab.index");
            };

            $rootScope.goProductIndex = function(){
                if(typeof Messenger != 'undefined') {
                    Messenger.sendMsg("ym_event",{eventID:"s28"},null,null);
                }
                $state.go("tab.product-index");
            };


            $rootScope.goAccountIndex= function(){
                if(typeof Messenger != 'undefined') {
                    Messenger.sendMsg("ym_event",{eventID:"s29"},null,null);
                }
                //获取缓存的用户信息
                var user = LocalCacheService.getUser();
                if(!user){
                    //取消默认跳转行为
                    event.preventDefault();
                    //跳转到登陆界面
                    var currentView = $ionicHistory.currentView();
                    $state.go("login",{from:currentView.stateName, fromParams: angular.toJson(currentView.stateParams),
                        w:'notLogin',to: "tab.account-index", toParams: ""});
                } else {
                    //取消默认跳转行为
                    event.preventDefault();
                    $state.go("tab.account-index");
                }

            };

            $rootScope.$on('$ionicView.beforeEnter', function () {
                var stateName = $state.current.name;
                $rootScope.hideTabs = false;
                if (stateName === 'tab.index' || stateName === 'tab.product-index'
                    || stateName === 'tab.account-index') {
                    $rootScope.hideTabs = false;
                } else {
                    $rootScope.hideTabs = true;
                }
            });

            //拦截
            $rootScope.$on('$stateChangeStart',function(event, toState, toParams, fromState, fromParams){

                if(typeof Messenger != 'undefined') {
                    if(fromState && fromState.name != "") {
                        Messenger.sendMsg("ym_endLogPageView",{pageID:fromState.url} ,null,null);
                    }
                    Messenger.sendMsg("ym_beginLogPageView",{pageID:toState.url} ,null,null);
                }

                if(typeof DigitalKeyboard != 'undefined') {
                    DigitalKeyboard.close(function(status){});
                }
                if(!toState.loginStatus && !toState.openStatus){ //未设置登录拦截、开户拦截的请求，直接跳转
                    return;
                }
                if(toState.loginStatus && !LocalCacheService.getUser()){ //登陆拦截
                    //取消默认跳转行为
                    event.preventDefault();
                    //跳转到登陆界面
                    $state.go("login",{from:fromState.name, fromParams: angular.toJson(fromParams),
                        w:'notLogin',to: toState.name, toParams: angular.toJson(toParams)});
                }
                if(toState.openStatus && !LocalCacheService.getOpenUser()){ //开户拦截
                    //取消默认跳转行为
                    event.preventDefault();
                    //跳转到手机验证页
                    $state.go("open-msgVerify");
                }
            });

            $rootScope.$on('userIntercepted',function(errorType, data){
                if($state.current.name != "login"){
                    $state.go("login",{from:$state.current.name,w:data});
                }
            });
            $rootScope.$on('openUserIntercepted',function(errorType, data){
                // 跳转到手机号验证界面
                $state.go("open-msgVerify");
            });
            var onReceiveMessage = function (event) {
                var message;
                if (device.platform == "Android") {
                    message = window.plugins.PushPlugin.receiveMessage.message;
                } else {
                    message = event.message;
                } if(typeof message != 'undefined') {
                    var bToObj = JSON.parse(message);
                    //var extras = window.plugins.PushPlugin.extras
                    var toView = bToObj.value.view;
                    if(typeof toView != 'undefined') {
                        var params = bToObj.value.params;
                        $state.go(toView,params);
                    }
                }
            };
            //APP在后台中，获取点击通知内容
            var onOpenNotification = function (event) {
                try {
                var alertContent;
                if (device.platform == "Android") {
                alertContent = window.plugins.PushPlugin.openNotification.alert;
                }
                else {
                alertContent = event.aps.alert;
                }
                console.log("open Notificaiton:" + alertContent);
                if(typeof alertContent != 'undefined')
                {
                 var bToObj = JSON.parse(alertContent.body);
                 //var extras = window.plugins.PushPlugin.extras
                 var toView = bToObj.value.view;
                 if(typeof toView != 'undefined')
                 {
                 var params = bToObj.value.params;
                 $state.go(toView,params);
                 }
                }
                }
                catch (exception) {
                console.log("PushPlugin:onOpenNotification" + exception);
                }
            };
            //APP在运行状态中，获取通知内容
            var onReceiveNotification = function (event) {
                try {
                var alertContent;
                if (device.platform == "Android") {
                alertContent = window.plugins.PushPlugin.receiveNotification.alert;
                } else {
                alertContent = event.aps.alert;
                }
                console.log("Receive Notificaiton:" + alertContent);
                if(typeof alertContent != 'undefined')
                {
                var bToObj = JSON.parse(alertContent.body);
                //var extras = window.plugins.PushPlugin.extras
                var toView = bToObj.value.view;
                if(typeof toView != 'undefined')
                {
                var params = bToObj.value.params;
                $state.go(toView,params);
                }
                }
                         
                }
                catch (exeption) {
                console.log(exception)
                }
            };

            document.addEventListener("push.receiveMessage", onReceiveMessage, false);
            document.addEventListener("push.openNotification", onOpenNotification, false);
            document.addEventListener("push.receiveNotification", onReceiveNotification, false);
        }]);
    
    return controllers;
});